#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class JilinYbcxzzzzrmzf329aPolicy(BaseTaxPolicySpider):
    name = 'jilin_ybcxzzzzrmzf_329a_policy'
    
    province = '吉林省'
    city = '延边朝鲜族自治州'
    park = ''
    
    def start_requests(self):
        for source, county, url in [
            ['延边朝鲜族自治州人民政府', '', 'http://zfxxgk.yanbian.gov.cn/cyqzf/gknr/lzyj/index.html'],
            ['延吉市人民政府', '延吉市', 'http://www.yanji.gov.cn/yjszfxxgkw/cyqzf/gknr/lzyj/index.html'],
            ['图们市人民政府', '图们市', 'http://www.tumen.gov.cn/tmszfxxgkw/cyqzf/gknr/lzyj/'],
            ['敦化市人民政府', '敦化市', 'http://www.dunhua.gov.cn/zw_2131/zfwj/index.html'],
            ['敦化市人民政府', '敦化市', 'http://www.dunhua.gov.cn/dhszfxxgkw/cyqzf/gknr/lzyj/'],
            ['龙井市人民政府', '龙井市', 'http://www.longjing.gov.cn/ljszfxxgkw/cyqzf/gknr/lzyj/'],
            ['珲春市人民政府', '珲春市', 'http://www.hunchun.gov.cn/hcszfxxgkw/cyqzf/gknr/lzyj/zfwj/'],
            ['龙井市人民政府', '龙井市', 'http://www.longjing.gov.cn/zw/wj/zfwj/'],
            ['和龙市人民政府', '和龙市', 'http://www.helong.gov.cn/zw_2395/wj/index.html'],
            ['和龙市人民政府', '和龙市', 'http://www.helong.gov.cn/hlszfxxgkw/cyqzf/gknr/lzyj/'],
            ['汪清县人民政府', '汪清县', 'http://www.wangqing.gov.cn/wqxzfxxgkw/cyqzf/gknr/lzyj/'],
            ['安图县人民政府', '安图县', 'http://www.antu.gov.cn/atxzfxxgkw/cyqzf/gknr/lzyj/'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        print(response.url)
        prev_item = response.meta.get('item')
        if '系统繁忙,请稍后点击' in response.text:
            yield scrapy.Request(response.url, callback=self.parse_list, dont_filter=True, meta={'item': prev_item, 'is_next': False})
        elem_list = response.xpath(
            "//table//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//div//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//div//tr//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=9] | "
            "//table//tr//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=9]")
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jsp' not in item['source_url']:
                continue
            if '/pdf/' in item['source_url'] or '/doc/' in item['source_url']:
                continue
            # print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下页' in response.text or '下一页' in response.text:
                totalpage = response.xpath(""".""").re_first(r"var countPage\s*=\s*(\d+)") or response.xpath(""".""").re_first(r"Pager\(\{size\:\s*(\d+)")
                print('totalpage', totalpage)
                if totalpage:
                    for page in range(1, int(totalpage) + 1):
                        url = response.url.replace('index.html', '') + f'index_{page}.html'
                        yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})
                else:
                    print(response.url)
            else:
                print(response.url)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("""string(//meta[@name='firstpublishedtime']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        # item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jilin_ybcxzzzzrmzf_329a_policy".split())
